package com.yi.wood.web.ctrl;

import com.yi.wood.entity.Role;
import com.yi.wood.service.po.UserCachePo;
import com.yi.wood.web.ctrl.dto.RoleParam;
import com.yi.wood.web.service.RoleProService;
import com.yi.wood.web.util.WoodBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author MoYi
 * create date 2019/4/6 15:16
 */
@Validated
@RestController
@RequestMapping(value = "/api/role/")
public class RoleCtrl extends BaseCtrl {

    @Resource
    private RoleProService roleProService;

    /**
     * 创建角色
     * @param param 角色信息
     * @return 角色信息
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object addRole(@RequestBody @Valid RoleParam param){
        Role role = new Role();
        BeanUtils.copyProperties(param, role);
        role.setStatus(1);
        role.setType(1);
        role = roleProService.addData(role);
        return success(role);
    }

    /**
     * 更新角色信息
     * @param param 角色信息
     * @return 角色信息
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Object updateRole(@RequestBody RoleParam param){
        Role role = new Role();
        BeanUtils.copyProperties(param, role, WoodBeanUtils.getNullPropertyNames(param));
        role = roleProService.addData(role);
        return success(role);
    }

    /**
     * 删除角色
     * @param roleId 角色ID
     * @return 结果
     */
    @RequestMapping(value = "/del/{roleId}",method = RequestMethod.DELETE)
    public Object deleteRole(@PathVariable Long roleId){
        roleProService.delData(roleId);
        return success();
    }

    /**
     * 返回所有角色信息列表
     * @return 角色列表
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public Object listAll(@RequestParam(required = false) String name,
                          @RequestParam(required = false) Integer status){
        return success(roleProService.queryAllRole(name, status));
    }

    /**
     * 查询用户所有的角色列表
     * @param userId 用户ID
     * @return 角色列表
     */
    @RequestMapping(value = "/list/userRoles",method = RequestMethod.GET)
    public Object listUserRoles(@RequestParam(required = false) Long userId){
        if (Objects.isNull(userId)){
            userId = ((UserCachePo)getUserByToken()).getUserId();
        }
        return success( roleProService.queryUserRole(userId));
    }

}
